package com.rycx.facefeatureclient.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.UUID;

public class Base64Util {
    static Logger log = LoggerFactory.getLogger(Base64Util.class);

    /**
     * @描述: 图片转base64字符串
     * @参数: @param imgFile 图片路径
     * @参数: @return base64码
     */
    public static String imageToBase64Str(String imgFilePath) {
        try {
            return imageToBase64Str(new FileInputStream(imgFilePath));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }

    }

    public static String imageToBase64Str(File imgFile){
        try {
            return imageToBase64Str(new FileInputStream(imgFile));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
    public static String imageToBase64Str(InputStream inputStream) throws Exception {
        if(inputStream==null){
            throw new Exception("请求参数错误");
        }
        byte[] data = null;
        try {
            int fileSize = inputStream.available();
            if(fileSize>100*1024*1024){
                throw new Exception("图片文件大于100M");
            }
            data = new byte[inputStream.available()];
            int count = 0;
            while((count=inputStream.read(data))> 0) {
                log.info("图片转BASE64码："+count);
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(),e);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }finally {
            try {
                if(null!=inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }
    /**
     * @描述: base64编码字符串转换为图片
     * @参数 @param imgStr base64编码字符串
     * @参数 @param path 图片路径
     * @参数 @return
     * @返回类型:boolean
     */
    public static boolean base64StrToImage(String imgStr, String path) {
        if (imgStr == null) {
            return false;
        }
        //文件夹不存在则自动创建
        File tempFile = new File(path);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
//        OutputStream out = null;
        try(OutputStream out = new FileOutputStream(tempFile)) {
            byte[] b = Base64.getDecoder().decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return false;
        }finally {

        }
    }

    public static String base64ToImg(String src) throws IOException {
        String uuid = UUID.randomUUID().toString();
        StringBuilder newPath = new StringBuilder("xx");
        newPath.append("xx").
                append(uuid).
                append("xx");
        if (src == null) {
            return null;
        }
        byte[] data = null;
//        OutputStream out = null;
        Base64.Decoder decoder = Base64.getDecoder();
        try(OutputStream out = new FileOutputStream(newPath.toString())) {
//            out = new FileOutputStream(newPath.toString());
            data = decoder.decode(src);
            out.write(data);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } finally {
        }
        return newPath.toString();
    }

    public static String getImgStrByUrl(String klUrl) {
        URL url = null;
        try {
            url = new URL(klUrl);
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        }
        try (InputStream in = url.openStream()) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer))!= -1) {
                out.write(buffer, 0, len);
            }
            byte[] imageBytes = out.toByteArray();
            String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
            return imageBase64;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static InputStream base64ToInputStream(String base64) {
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }
}
